import React, { useState, useEffect, useMemo } from "react";
import { CommonModal } from "@/views/components/CommonModal";
import { Select, Form, message } from "antd";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { updatePrintStatus } from "../service";

import { usePrintUniqueCode } from "@/views/hooks/usePrintUniqueCode";

const PrintModal = ({ visible, type, printParams, handleOk, handleCancel, ApiData, printType, getUpdatePrint }) => {
	const {
		printUniqueCode,
		initPrint,
		template,
		printData,
		printerList,
		uniqueCodePrinter,
		getPrintDataFunc,
		configObj,
		printAction,
		printSuccess,
		getExpressRelativePrinter,
		setUniqueCodeRelativePrinter
	} = usePrintUniqueCode({
		callback: data => {
			console.log(data, "datassssssssssssssss");
			if (data.printData) {
				if (data.printData.length > 10000) {
					processData(data.printData, 1000);
				} else {
					updatePrintStatus([...data?.printData?.map(e => e.uniqueCode)]).then(res => {
						if (res.success) {
							handleCancel();
							fetchList();
						}
					});
				}
			}
		},
		ApiData,
		printType
	});
	async function sendDataToApi(chunk) {
		// 发送数据到接口的逻辑
		// 这里只是一个示例，你需要根据你的实际情况来实现发送数据的逻辑
		const response = await updatePrintStatus(chunk);
		// if (!response.ok) {
		// 	throw new Error("Network response was not ok");
		// }

		return response;
	}

	async function processData(list, chunkSize) {
		let startIndex = 0;
		let endIndex = chunkSize;

		while (startIndex < list.length) {
			if (endIndex > list.length) {
				endIndex = list.length;
			}

			const chunk = list?.slice(startIndex, endIndex)?.map(e => e.uniqueCode);
			await sendDataToApi(chunk);

			startIndex += chunkSize;
			endIndex += chunkSize;
		}
	}
	const [form] = Form.useForm();

	useEffect(() => {
		for (let i = 0; i < printParams.length; i++) {
			printParams[i].nums = i + 1;
		}
		const d = printParams.map(e => {
			return {
				uniqueCode: e.code, //"条形码",
				codeSN: e.nums, // "序号",
				orderGoodsCount: e.skuQuantity, //"订单商品数量",
				orderGoodsName: e.skuName, // "订单商品名称",
				orderGoodsSpec: e.skuSpec, //"订单规格属性",
				salesOrderSn: e.outboundNo // "销售出库单号"
			};
		});
		const obj = getExpressRelativePrinter() || {};
		form.setFieldsValue({
			printer: obj["唯一码"]
		});
		form.setFieldValue("唯一码", obj["唯一码"]);
		if (visible) initPrint(d);
	}, [visible, printParams, configObj]);
	//获取打印数据推入队列
	const onOk = () => {
		if (!printParams?.length) {
			return message.info("打印数据为空");
		}
		form.validateFields().then(value => {
			if (!value) {
				return message.info("请选择打印机");
			}
			// printAction([template, printData, value["唯一码"]]);
			handleOk(template, printData, value["唯一码"]);
			setTimeout(() => {
				handleCancel();
			}, 2000);
		});
	};

	// 设置打印机名称
	const handlePrinterName = name => {
		setUniqueCodeRelativePrinter(name);
	};

	const options =
		Array.isArray(printerList) &&
		printerList.map(d => (
			<Option key={d} value={d}>
				{d}
			</Option>
		));

	return (
		<CommonModal
			title={{ title: "唯一码打印" }}
			visible={visible}
			onCancel={handleCancel}
			width="553px"
			onOk={onOk}
			minHeight={138}
		>
			<Form form={form} name="common-printer-select">
				<SubTitle symbol as="s2" title={`打印详情`} wrapStyle={{ marginBottom: 16 }} />
				<Form.Item style={{ margin: 8 }}>
					<div>
						<span>打印唯一码数量：</span>
						<span style={{ color: "rgba(240, 61, 41, 1)" }}>{printData.length}</span>
					</div>
				</Form.Item>
				{configObj && (
					<Form.Item label="" name="唯一码" style={{ margin: 8 }} rules={[{ required: true, message: "请先选择打印机" }]}>
						<Select placeholder="请选择打印机" onChange={handlePrinterName} value={configObj["唯一码"]}>
							{options}
						</Select>
					</Form.Item>
				)}
			</Form>
		</CommonModal>
	);
};

export default PrintModal;
